import os
import pickle
import random,json
from typing import List

import uvicorn
from fastapi import FastAPI, File, Request, UploadFile,Form
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from starlette.responses import FileResponse
from starlette.responses import JSONResponse

from manager import Manager

# 准备工作


master = Manager()
master.loadInviteCodes()

# 开启服务
app = FastAPI()


class FileModel(BaseModel):
    name: str=''
    passwd: str=''
    fileName: str=''   

'''

@app.exception_handler(RequestValidationError)
async def request_validation_exception_handler(request: Request, exc: RequestValidationError):
    print(f"参数不对{request.method} {request.url}")
    # return JSONResponse({"code": "400", "message": exc.errors()})
'''

@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get('/signin/')
async def signin(name, passwd, email, invitecode):
    master.loadInviteCodes()
    if invitecode in master.inviteCodes:
        master.addUser(name, passwd, email, invitecode)
        return {
            'status': 'yes',
            'info': '注册成功',
            'name': name,
        }
    else:
        return {
            'status': 'no',
            'info': '请求非法',
        }


@app.get('/signon/')
async def signon(name, passwd):
    ID = master.checkNameAndPasswd(name, passwd)
    if ID == 0:
        return {
            'status': 'no',
            'info': '用户不存在或密码错误',
        }
    else:
        return {
            'status': 'yes',
            'info': '登录成功',
            'ID': ID
        }


@app.get('/getFilesList/')
async def getFilesList(name, passwd):
    ID = master.checkNameAndPasswd(name, passwd)
    if ID:
        return{
            'status': 'yes',
            'info': master.getFilesInfoById(ID)
        }
    else:
        return {
            'status': 'no',
            'info': '登录失败',
        }



@app.post('/upload/')
async def upload(
    name:str=Form(...),
    passwd:str=Form(...),
    fileName:str=Form(...),
    relaPath:str=Form(...),
    file:UploadFile=File(...),
    ):
    content= await file.read()
    ID=master.checkNameAndPasswd(name,passwd)   
    if ID:
        if relaPath=='哎呀好奇怪':
            folderPath = os.path.join(master.filesPath,str(ID))
        else:
            folderPath = os.path.join(master.filesPath,str(ID),relaPath)
                
        if not os.path.isdir(folderPath):
            os.makedirs(folderPath)
        filePath=os.path.join(folderPath,fileName)
        with open(filePath ,'wb+') as f:
            f.write(content)   
        return {
            'status': 'yes',
            'info': f'{fileName}上传成功',
        }
    else:
        return {
            'status': 'no',
            'info': '登录失败',
        }

@app.get('/download/')
async def dowload(name, passwd,relaPath,fileName):
    ID = master.checkNameAndPasswd(name, passwd)    
    if ID:
        path=os.path.join(master.filesPath,str(ID),relaPath,fileName)
        return FileResponse(path,status_code=200,filename=fileName)
    else:
        return JSONResponse({
            'status':'no',
            'info':'登录失败',
        },status_code=403)
@app.post('/delete/')
async def delete(
    name:str=Form(...),
    passwd:str=Form(...),
    fileName:str=Form(...),
    relaPath:str=Form(...),
    ):
    ID=master.checkNameAndPasswd(name,passwd)  
    if relaPath=='哎呀好奇怪':
        relaPath=''
    if ID:
        path=os.path.join(master.filesPath,str(ID),relaPath,fileName)
        os.remove(path)
        return {
            'status':'yes',
            'info':'删除成功',
        }
    else:
        return {
            'status': 'no',
            'info': '登录失败',
        }






if __name__ == "__main__":
    uvicorn.run("service:app", host="127.0.0.1", port=8000, log_level="info")
